"""
客服聊天
"""
from flask import Blueprint, render_template, request, jsonify
from apps.common.utils.rights import authorize
from apps.common.utils.http import success_api, fail_api, table_api
from apps.common.curd import model_to_dicts
from apps.modules.admin.models.cms.cms_chat import ChatRecord, ChatSession
from apps.modules.admin.schemas import ChatRecordOutSchema, ChatSessionOutSchema
from apps.extensions import db
from sqlalchemy import desc, func
import datetime

chat_bp = Blueprint('chat', __name__, url_prefix='/chat/io')

@chat_bp.get('/')
@authorize("cms:chat:main")
def index():
    """聊天记录查看页面"""
    return render_template('cms/chat/main.html')
@chat_bp.route('/live')
@authorize("cms:chat:live", log=True)
def live():
    """实时聊天页面"""
    return render_template('cms/chat/chat_live.html')

@chat_bp.get('/sessions')
@authorize("cms:chat:main")
def get_sessions():
    """获取聊天会话列表"""
    page = request.args.get('page', type=int, default=1)
    limit = request.args.get('limit', type=int, default=10)
    status = request.args.get('status', '')
    user_name = request.args.get('user_name', '')
    user_phone = request.args.get('user_phone', '')
    
    query = ChatSession.query
    
    # 添加筛选条件
    if status:
        query = query.filter(ChatSession.status == status)
    if user_name:
        query = query.filter(ChatSession.user_name.like(f'%{user_name}%'))
    if user_phone:
        query = query.filter(ChatSession.user_phone.like(f'%{user_phone}%'))
    
    # 按创建时间倒序排列
    query = query.order_by(desc(ChatSession.create_time))
    
    # 分页
    pagination = query.paginate(page=page, per_page=limit, error_out=False)
    sessions = pagination.items
    total = pagination.total
    
    # 转换为字典
    data = model_to_dicts(schema=ChatSessionOutSchema, data=sessions)
    
    return table_api(data=data, count=total)

@chat_bp.get('/records/<session_id>')
@authorize("cms:chat:main")
def get_records(session_id):
    """获取指定会话的聊天记录"""
    page = request.args.get('page', type=int, default=1)
    limit = request.args.get('limit', type=int, default=50)
    
    query = ChatRecord.query.filter(ChatRecord.session_id == session_id)
    query = query.order_by(ChatRecord.create_time)
    
    pagination = query.paginate(page=page, per_page=limit, error_out=False)
    records = pagination.items
    total = pagination.total
    
    data = model_to_dicts(schema=ChatRecordOutSchema, data=records)
    
    return table_api(data=data, count=total)

@chat_bp.get('/session/<session_id>')
@authorize("cms:chat:main")
def get_session_detail(session_id):
    """获取会话详情"""
    session = ChatSession.query.filter(ChatSession.session_id == session_id).first()
    if not session:
        return fail_api(msg="会话不存在")
    
    data = ChatSessionOutSchema().dump(session)
    return success_api(data=data)

@chat_bp.delete('/session/<session_id>')
@authorize("cms:chat:delete")
def delete_session(session_id):
    """删除会话"""
    session = ChatSession.query.filter(ChatSession.session_id == session_id).first()
    if not session:
        return fail_api(msg="会话不存在")
    
    try:
        # 删除会话相关的所有聊天记录
        ChatRecord.query.filter(ChatRecord.session_id == session_id).delete()
        # 删除会话
        db.session.delete(session)
        db.session.commit()
        return success_api(msg="删除成功")
    except Exception as e:
        db.session.rollback()
        return fail_api(msg=f"删除失败: {str(e)}")

@chat_bp.get('/stats')
@authorize("cms:chat:main")
def get_stats():
    """获取聊天统计信息"""
    # 今日会话数
    today = datetime.datetime.now().date()
    today_sessions = ChatSession.query.filter(
        func.date(ChatSession.create_time) == today
    ).count()
    
    # 总会话数
    total_sessions = ChatSession.query.count()
    
    # 活跃会话数
    active_sessions = ChatSession.query.filter(ChatSession.status == 'active').count()
    
    # 今日消息数
    today_messages = ChatRecord.query.filter(
        func.date(ChatRecord.create_time) == today
    ).count()
    
    # 总消息数
    total_messages = ChatRecord.query.count()
    
    data = {
        'today_sessions': today_sessions,
        'total_sessions': total_sessions,
        'active_sessions': active_sessions,
        'today_messages': today_messages,
        'total_messages': total_messages
    }
    
    return success_api(data=data)